package com.heima.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.mapper.TbRoleMapper;
import com.heima.pojo.TbRole;
import com.heima.pojo.TbUser;
import com.heima.mapper.TbUserMapper;
import com.heima.pojo.dto.TbUserDto;
import com.heima.pojo.vo.PageResponse;
import com.heima.pojo.vo.TbRoleVo;
import com.heima.pojo.vo.TbUserVo;
import com.heima.service.ITbUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author AkiRinko
 * @since 2024-06-10
 */
@Service
@RequiredArgsConstructor
public class TbUserServiceImpl extends ServiceImpl<TbUserMapper, TbUser> implements ITbUserService {
    private final TbUserMapper tbUserMapper;

    private final TbRoleMapper tbRoleMapper;

    /**
     * 人员搜索
     *
     * @param pageIndex
     * @param pageSize
     * @param userName
     * @return
     */
    @Override
    public PageResponse<TbUserVo> selectUserPage(Integer pageIndex, Integer pageSize, String userName) {
        Page<TbUserVo> page = new Page<>(pageIndex, pageSize);
        Page<TbUserVo> result = tbUserMapper.selectUserPage(userName, page);

        return PageResponse.of(result);
    }

    /**
     * 角色列表
     *
     * @return
     */
    @Override
    public List<TbRoleVo> selectRoleList() {
        LambdaQueryWrapper<TbRole> wrapper = new LambdaQueryWrapper<>();
        List<TbRole> list = tbRoleMapper.selectList(wrapper);

        return BeanUtil.copyToList(list, TbRoleVo.class);
    }

    /**
     * 新增人员
     *
     * @param dto
     */
    @Override
    public void insertUser(TbUserDto dto) {
        if ("true".equals(dto.getStatus())) {
            dto.setStatus("1");
        } else {
            dto.setStatus("0");
        }
        TbUser tbUser = BeanUtil.copyProperties(dto, TbUser.class);

        tbUserMapper.insert(tbUser);
    }

    /**
     * 修改人员
     *
     * @param userId
     * @param dto
     */
    @Override
    public void updateUser(Integer userId, TbUserDto dto) {
        if ("true".equals(dto.getStatus())) {
            dto.setStatus("1");
        } else {
            dto.setStatus("0");
        }
        TbUser tbUser = BeanUtil.copyProperties(dto, TbUser.class);

        LambdaQueryWrapper<TbUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TbUser::getId, userId);

        tbUserMapper.update(tbUser, wrapper);
    }

    /**
     * 删除人员
     *
     * @param userId
     */
    @Override
    public void deleteUser(Integer userId) {
        tbUserMapper.deleteById(userId);
    }


}
